<template>
  <DynamicList
    ref="attractionsListTable"
    v-bind="attractionsListColumns"
    @load-data="setPage"
    @reset-data="onResetData"
  >
    <template #tableTop>
      <a-space class="flex-wrap" size="small">
        <a-button
          v-if="$auth('attractions-add')"
          type="primary"
          @click="router.push('/attractions/attractionsEdit')"
        >
          <PlusOutlined />
          新增
        </a-button>
      </a-space>
    </template>
    <template #searchQuery>
      <div>
        <span class="pr-8px">景点类型：</span>
        <a-select
          v-model:value="queryData.type"
          class="min-w-150px"
          allow-clear
          :options="typeList"
          placeholder="请选择景点类型"
        ></a-select>
      </div>
      <div>
        <span class="pr-8px">景点等级：</span>
        <a-select
          v-model:value="queryData.grade"
          class="min-w-150px"
          allow-clear
          :options="gradeList"
          placeholder="请选择景点等级"
        ></a-select>
      </div>
      <div class="inline-flex items-center">
        <span class="pr-8px">发布时间：</span>
        <a-range-picker
          v-model:value="publishDate"
          :format="valueFormat"
          show-time
          @change="(date, dateString) => onRangeChange('publishDate', dateString)"
        />
      </div>
    </template>
  </DynamicList>
</template>

<script setup lang="tsx">
  import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { Avatar, message, Modal, Tag } from 'ant-design-vue';
  import type { Dayjs } from 'dayjs';
  import { deleteAttractions, attractionsApi, enabledAttractions } from '@/api/attractions';
  import { formatToDateTime } from '@/utils/dateUtil';
  import DynamicList from '@/components/dynamicList/index.vue';
  import { RequestEnum } from '@/enums/httpEnum';
  import { publicPathUrl } from '@/utils/common';
  import useRequestList from '@/hooks/useRequestList';
  import { verifyAuth } from '@/core/permission';
  import { getFileHttpUrl } from '@/utils/urlUtils';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { publishOptions, StatusEnum } from '@/enums/DisableEnum';
  import { useUserStore } from '@/store/modules/user';
  import { categoryJsonByType } from '@/api/category';
  import { categoryTypeEnum } from '@/enums/categoryTypeEnum';

  defineOptions({
    name: 'attractionsList',
  });

  const userStore = useUserStore();
  const rusticId = userStore.getRusticId();

  const valueFormat = 'YYYY-MM-DD HH:mm';
  const typeList = ref<{ id: number; name: string }[]>([]);
  const gradeList = ref<{ id: number; name: string }[]>([]);
  const attractionsListTable = ref<any>(null);
  const router = useRouter();

  type RangeValue = [Dayjs, Dayjs];
  interface QueryDataParams {
    endPublishTime: string;
    startPublishTime: string;
    type: number | null;
    grade: number | null;
  }
  const publishDate = ref<RangeValue | string[]>();
  const queryData = reactive<QueryDataParams>({
    endPublishTime: '',
    startPublishTime: '',
    type: null,
    grade: null,
  });

  const { list, page, setPage, loading } = useRequestList({
    apiKey: attractionsApi.attractionsList,
    type: RequestEnum.GET,
    initParam: {
      rusticId,
    },
  });
  const attractionsListColumns = ref({
    columns: [
      {
        title: '序号',
        width: 30,
        align: 'center',
        dataIndex: 'index',
        fixed: 'left',
        customRender: ({ record, text, index }) => index + 1,
      },
      {
        title: '封面',
        width: 80,
        align: 'center',
        fixed: 'left',
        dataIndex: 'cover',
        customRender: ({ text }) => {
          return text ? <a-image width="80px" src={getFileHttpUrl(text)} /> : '-';
        },
      },
      {
        title: '景点名称',
        width: 80,
        align: 'center',
        fixed: 'left',
        dataIndex: 'name',
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      {
        title: '地址',
        width: 100,
        align: 'center',
        dataIndex: 'address',
      },
      {
        title: '景点等级',
        width: 80,
        align: 'center',
        dataIndex: 'gradeName',
      },
      {
        title: '景点类型',
        width: 80,
        align: 'center',
        dataIndex: 'typeName',
      },
      {
        title: '排序',
        width: 60,
        align: 'center',
        dataIndex: 'sort',
      },
      {
        title: '景点特色',
        width: 80,
        align: 'center',
        dataIndex: 'feature',
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      {
        title: '价格',
        width: 60,
        align: 'center',
        dataIndex: 'price',
      },
      {
        title: '发布时间',
        width: 80,
        align: 'center',
        dataIndex: 'publishTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '更新时间',
        width: 80,
        align: 'center',
        dataIndex: 'updateTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '创建时间',
        width: 80,
        align: 'center',
        dataIndex: 'createTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '状态',
        width: 100,
        align: 'center',
        fixed: 'right',
        dataIndex: 'status',
        search: true,
        component: ComponentsTypeEnum.Select,
        componentProps: {
          options: publishOptions,
        },
        customRender: ({ record }) => {
          return (
            <a-switch
              onChange={() => updateStatus(record)}
              v-model:checked={record.status}
              un-checked-value={StatusEnum.DISABLED}
              checked-value={StatusEnum.NORMAL}
              un-checked-children={'已下架'}
              checked-children={'已发布'}
            />
          );
        },
      },
      {
        title: '操作',
        width: 150,
        dataIndex: 'operation',
        align: 'center',
        fixed: 'right',
        actions: [
          {
            title: '详情',
            vIf: verifyAuth('attractions-detailPage'),
            onClick: (record) => {
              router.push(`/attractions/attractionsDetail?id=${record.id}`);
            },
          },
          {
            title: '编辑',
            vIf: verifyAuth('attractions-update'),
            onClick: (record) => {
              router.push(`/attractions/attractionsEdit?id=${record.id}`);
            },
          },
          {
            title: '删除',
            vIf: verifyAuth('attractions-delete'),
            onClick: (record) => {
              deleteConfirmAttractions(record);
            },
          },
        ],
      },
    ],
    queryParamsSlots: queryData,
    pageParams: page,
    list,
    loading,
    columnProps: {
      scroll: {
        x: 'calc(100vw - 200px)',
      },
      bordered: true,
    },
  });

  const deleteConfirmAttractions = async (record) => {
    Modal.confirm({
      title: '确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      centered: true,
      onOk: async () => {
        const res = await deleteAttractions({ id: record.id });
        if (res) {
          message.success(res?.msg);
          attractionsListTable.value && attractionsListTable.value.resetFields();
        }
      },
    });
  };

  const updateStatus = async (record: { id: number }) => {
    const res = await enabledAttractions({ id: record.id });
    if (res) {
      message.success(res?.msg);
      attractionsListTable.value && attractionsListTable.value.resetFields();
    }
  };

  const onResetData = (queryParams: Object) => {
    for (const queryParamsKey in queryData) {
      queryData[queryParamsKey] = null;
    }
    publishDate.value = [queryData.startPublishTime, queryData.endPublishTime];
    setPage(queryParams);
  };

  const onRangeChange = (type: string, dateString: string[]) => {
    if (type === 'publishDate') {
      queryData.startPublishTime = dateString[0];
      queryData.endPublishTime = dateString[1];
    }
  };

  const getCategoryList = async () => {
    const res = await categoryJsonByType({ type: categoryTypeEnum.ATTRACTION_TYPE });
    if (res) {
      typeList.value = res.data.map((item: { name: string; id: number }) => ({
        label: item.name,
        value: item.id,
      }));
    }
    const gradeRes = await categoryJsonByType({ type: categoryTypeEnum.ATTRACTION_GRADE });
    if (gradeRes) {
      gradeList.value = gradeRes.data.map((item: { name: string; id: number }) => ({
        label: item.name,
        value: item.id,
      }));
    }
  };

  onMounted(() => {
    getCategoryList();
  });
</script>

<style></style>
